<?php

class CategoryModel extends Model{
	
	public $table='category';
	
	public $validate=array(
		array('cname','nonull','分类名称不能为空',2,3),
	);
	
	public function get_all_data($where=null){
		
		  //查询所有数据并按csort排序后返回
		  $data = $this->where($where)->order('csort ASC')->all();
		  //格式化树状的数据
		  $data = Data::tree($data,'cname','cid','pid');
		  //返回数据
		  return $data;
	}
	
	public function get_all_data_notree($where=null,$limit=1000){
		
		return $this->where($where)->limit($limit)->all();
	}
	
	public function add_data(){
		
		return $this->add();
	}
	
	
	public function delete_data($where=null){
		
		$data=$this->where(array('pid'=>Q('get.cid')))->find();
		if($data){
			$this->error='请先删除其下子集';
			return FALSE;
		}
		return $this->where($where)->delete();
	}
	
	public function add_son_data(){
		
		if(!$this->create()) return FALSE;
		$data=array(
			'tid'=>Q('post.tid'),
			'cname'=>Q('post.cname'),
			'pid'=>Q('get.cid'),
		);
		
		return $this->add($data);
	}
	
	
	public function get_tid($where=null){
		 return $this->where($where)->getField('tid',true);
	}
	
	
	public function get_one_data($where=null){
		
		return $this->where($where)->find();
	}
	
	public function edit_data($where=null){
		
		if(!$this->create()) return FALSE;
		return $this->where($where)->update();
	}
	
	public function get_top_cid($cid){
		
		$data=$this->where(array('cid'=>$cid))->getField('pid',TRUE);
//		p($data);
		foreach ($data as $k => $v) {
			if($data[$k]!=0) $data=array_merge($data,$this->get_top_cid($v));
		}
		return $data;
		
	}
	
	public function get_son_cid($cid){
		$data=$this->get_all_data_notree();
		$temp=array();
		foreach ($data as $k => $v) {
			if($v['pid']==$cid){
				$temp[] = $v['cid'];
				$temp = array_merge($temp,$this->get_son_cid($v['cid']));
			}
		}
//		p($data);die;
		return $temp;
		
	}
	
}















